define(function(require, exports, module) {
  var $ = require("$");
  require("bootstrap_commonrequire");
  require("moment");
  require("bootstrap-daterangepicker");
  require("daterangepicker.css");

  /* 监听窗口大小变化，增强jquery的resize方法，可以激情dom元素 */
  require('js/core/jquery/src/jquery_resize');

  /* 添加ztree引用 */
  require("zTreeStyle.css");
  require("ztreeCore");
  require("ztreeExcheck");

  require('select2.css');
  require('select2');
  var store = require('store');
  var bootbox = require('bootbox');
  var loader = require("./loader/loader");

  exports.init = function(param) {
    $(document).ready(
      function() {
        // 蒙版
        loader.loading("数据加载中，请稍后……");
        // 加载自定义模板-条件区域
        var isSystemAdmin = (store.get("userInfo").userType == -1);
        var tplattrs = {};
        tplattrs.isSystemAdmin = isSystemAdmin;
        
        var startIndex;
  
        var template = require("./phonebill.tpl");
        var Widget = require("widget");
        var Component = Widget.extend({
          template : template
        });
        new Component({
          attrs : tplattrs,
          renderTo : queryAreaId
        });
        // 获取隐藏域中的查询条件
        var _carrierid = localStorage.getItem("_carrierid");
        var _carriertext = localStorage.getItem("_carriertext");
        var _isvid = localStorage.getItem("_isvid");
        var _applyid = localStorage.getItem("_applyid");
        var _sessionid = localStorage.getItem("_sessionid");
        var _starttimes = localStorage.getItem("_starttimes");
        var _endtimes = localStorage.getItem("_endtimes");
        var _start = localStorage.getItem("_start");
        var _abilityType = localStorage.getItem("_abilityType");
        //清空缓存中的信息
        localStorage.setItem("_carrierid","");
        localStorage.setItem("_carriertext","");
        localStorage.setItem("_isvid","");
        localStorage.setItem("_applyid","");
        localStorage.setItem("_sessionid","");
        localStorage.setItem("_starttimes","");
        localStorage.setItem("_endtimes","");
        localStorage.setItem("_start","");
        localStorage.setItem("_abilityType","");
  
        // 获取查询条件
        function getCondition() {
  
          var carrierid = $('#carrierid').val();
  
          var isvid = $('#isvid').val();
  
          var applyid = $('#applicationid').val();
  
          var sessionid = $('#sessionid').val();
          
          var abilityType = $('#abilityType').val();
  
          var queryStr = "";
  
          if (carrierid != '' && carrierid != null) {
            queryStr += ("corpid=" + carrierid + ";");
          }
  
          if (isvid != '' && isvid != null) {
            queryStr += ("isvid=" + isvid + ";");
          }
  
          if (applyid != '' && applyid != null) {
            queryStr += ("applyid=" + applyid + ";");
          }
  
          if (sessionid != '' && sessionid != null) {
            queryStr += ("sessionId=" + sessionid + ";");
          }
          
          if (abilityType != '' && abilityType != null) {
            queryStr += ("abilityType=" + abilityType + ";");
          }
  
          var dateranges = daterangeCom.getPickerRange();
          if (dateranges != '' && dateranges != null) {
            var daterange = dateranges.split("/");
            var startTime = daterange[0];
            var endTime = daterange[1];
  
            // 将查询条件藏在隐藏域中--用于后面返回时用于信息回执
            $('#_starttimes').val(startTime);
            $('#_endtimes').val(endTime);
            queryStr += "startTime=" + startTime + ";"
            queryStr += "endTime=" + endTime + ";";
          }
          // 将查询条件藏在隐藏域中--用于后面返回时用于信息回执
          $('#_carrierid').val(carrierid);
          $('#_isvid').val(isvid);
          $('#_applicationid').val(applyid);
          $('#_sessionid').val(sessionid);
          $('#_abilityType').val(abilityType);
          
          var carrierid_object=$("#carrierid").select2("data");
          if(carrierid_object!=null&&carrierid_object!=""&&carrierid_object!="undefined"){
            var carrierid_tmp=carrierid_object.text;
            if(carrierid_tmp!=null&&carrierid_tmp!=""&&carrierid_tmp!="undefined"){
              $('#_carriertext').val(carrierid_tmp);
            }
          }
          
          return queryStr;
        }
  
        // 绑定isv名称下拉列表
        $.ajax({
          type : "POST",
          dataType : "json",
          url : "/user/queryIsv.do",// GLOBAL.URL.ADMIN_GETCARRIEROPTIONS,//
                                        // wp.huang
          async : false,
          success : function(data) {
            $("#isvid").select2({
              placeholder : "ISV名称",
              allowClear : true,
              data : data
            });
            //将已选择的查询条件放入选择框
            $('#isvid').select2("val", _isvid);
          },
          error : function(data) {
            bootbox.alertTimeout('初始化ISV名称数据失败！');
          }
        });
  
        // 绑定应用下拉列表
        $.ajax({
          type : "POST",
          dataType : "json",
          url : "/condition/applyName.do",// /GLOBAL.URL.GETAPPLYTYPELIST,
                                          // ////wp.huang
          async : false,
          success : function(data) {
            $("#applicationid").select2({
              placeholder : "应用名称",
              allowClear : true,
              data : data
            });
          //将已选择的查询条件放入选择框
            $('#applicationid').select2("val", _applyid);
          },
          error : function(data) {
            bootbox.alertTimeout('初始化应用名称数据失败！');
          }
        });
        $("#carrierid").attr("value", _carrierid);
        $("#carrierid").select2({
          placeholder: "企业名称",
          allowClear: true,
          initSelection: function (element, callback) {
            //var data = [{id:_carrierid, text:"测试电话会议－何珍创建的企业"}];
            callback({id:_carrierid,text:_carriertext});//这里初始化
          },
          formatNoMatches: "没有匹配的企业",
          ajax: {
            url: GLOBAL.URL.ADMIN_GETCARRIEROPTIONS,
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) {
              return {
                q: " c.name like '%"+term+"%' ", // search term
                appid: $("#appid").val(),
                size: 25,
                start: (pageNo-1)*25
              };
            },
            results: function (data, pageNo) {
              var dataObj = eval(data);
              return {results:dataObj};
            },
            cache: true
          }
        });
        
        // 能力类型
        var typeList = [ {
          "id" : "TalksV2",
          "text" : "IMS多方通话"
        }, {
          "id" : "ScheduleConference",
          "text" : "专业会议"
        }, {
          "id" : "EcpMeet",
          "text" : "ECP多方通话"
        }, {
          "id" : "EcpDial",
          "text" : "ECP点击拨号"
        }, {
          "id" : "Dial",
          "text" : "IMS点击拨号"
        }, {
          "id" : "VoiceNotice3",
          "text" : "IMS文字语音短信"
        }, {
          "id" : "AudeoSend",
          "text" : "IMS语音留言"
        } ];
        $('#abilityType').select2({
          placeholder : "能力类型",
          allowClear : true,
          data : typeList
        });
  
        // 初始化日期范围选择控件
        var DateRange = require('daterangeinput');
        var daterangeAttrs = {
          daterangeId : "querydatewrapper_rang",
          label : "日期"
        };
        var daterangeCom = new DateRange({
          attrs : daterangeAttrs,
          renderTo : 'querydatewrapper'
        });
        daterangeCom.setRangeToToday();
        
        // 将隐藏域中的查询条件赋值给查询条件输入框
        $('#sessionid').val=_sessionid;
        
        if(_starttimes!=null&&_starttimes!="undefined"&&_starttimes!=""&&_endtimes!=null&&_endtimes!=""&&_endtimes!="undefined"){
          daterangeCom.setRangeToStartEnd(_starttimes, _endtimes);
        }else{
          daterangeCom.setRangeToToday();
        }
  
        // 加载表单模板和数据
        var Table = require("table");
        new Table({
          attrs : {
            id : "datatableid",
            isHovered : false,
            isStriped : true,
            isBordered : false
          },
          renderTo : param.divWrapperId
  
        });
  
        var dtUtil = require('datatableutil');
  
        var datatable = $('#datatableid')
            .dataTable(
                {
                  "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
                  "bJQueryUI" : false,
                  "oLanguage" : {
                    "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
                  },
                  "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
                  'bPaginate' : true, // 是否分页
                  "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
                  "bServerSide" : true, // 指定服务器端分页
                  "bDeferRender" : true,
                  "bFilter" : true,
                  "bSort" : true,
                  "bInfo" : true,
                  "sAjaxSource" : "/data/queryPhoneBill.do", // 数据源
                  "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
                  "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
  
                    var queryparam = dtUtil.convert_aoData(aoData);

                    startIndex = queryparam.start;
                    if(_start != null && _start!=''){
                      queryparam.start = _start;
                      _start = null;
                    }
  
                    // 拼接where查询条件
                    var cond = getCondition();
                    if (cond != '' && cond != null) {
                      queryparam.q += cond;
                    }
  
                    // 添加自己的额外参数
                    oSettings.jqXHR = $.ajax({
                      "dataType" : 'json',
                      "contentType" : "application/json;charset=UTF-8",
                      "type" : "GET",
                      "url" : sSource,
                      "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
                      "success" : function(json) {
                        // 隐藏蒙版
                        loader.noloading();
                        dtUtil.successCallback(json, aoData, fnCallback);
                      }
                    });
  
                  },
                  "aoColumns" : [
                      {
                        "sTitle" : "企业",
                        "bSortable" : false,
                        "mData" : "carriername",
                        "sWidth" : "12%"
                      },
                      {
                        "sTitle" : "ISV",
                        "bSortable" : false,
                        "mData" : "isvname",
                        "sWidth" : "12%"
                      },
                      {
                        "sTitle" : "应用",
                        "bSortable" : false,
                        "mData" : "applicationname",
                        "sWidth" : "12%"
                      },
                      {
                        "sTitle" : "会话ID",
                        "bSortable" : false,
                        "mData" : "sessionid",
                        "bVisible" : false
                      },
                      {
                        "sTitle" : "能力类型",
                        "bSortable" : false,
                        "mData" : "ability_type",
//                        "sWidth" : "15%",
                        "mRender" : function(data, type, full) {
                          if (data == "TalksV2")
                            return "IMS多方通话";
                          else if (data == "Dial")
                            return "IMS点击拨号";
                          else if (data == "ScheduleConference")
                            return "专业会议";
                          else if(data == "sms")
                            return "短信";
                          else if(data == "EcpDial")
                            return "ECP点击拨号";
                          else if(data == "EcpMeet")
                            return "ECP多方通话";
                          else if(data == "VoiceNotice3")
                            return "IMS文字语音短信";
                          else if(data == "AudeoSend")
                            return "IMS语音留言";
                          else
                            return "未知";
                        }
                      },
                      {
                        "sTitle" : "通话开始时间",
                        "bSortable" : false,
                        "mData" : "callingtime"
                      },
                      {
                        "sTitle" : "通话时长(分钟)",
                        "bSortable" : false,
                        "mData" : "callingduration",
                        "sWidth" : "10%",
                        "mRender" : function(data, type, full) {
                            return "<div class='fontcir' style='margin-left:40px;'>"+data+"</div>";
                        }
                      },
  
                      {
                        "sTitle" : "主叫号",
                        "bSortable" : false,
                        "mData" : "callingnum"
                      },
  
                      {
                        "sTitle" : "参会人数量",
                        "bSortable" : false,
                        "mData" : "callednum",
                        "sWidth" : "8%",
                        "mRender" : function(data, type, full) {
                          var ret = '<div class="btn-group" style="margin-top: 8px;">';
                          ret = ret
                              + '<a href="javascript:void(0);" class="btn btn-link" style="text-decoration:underline;margin-top:-16px;margin-left:20px;" title="明细" aid='
                              + data + '>' + full.callednum + '</a>';
                          return ret += '</div>';
                        }
                      }, {
                        "sTitle" : "接收状态",
                        "bSortable" : false,
                        "mData" : "isAccepted",
                        "sWidth" : "7%",
                        "mRender" : function(data, type, full) {
                          if (data == "1" || data == "１")
//                            return "处理成功";
                            return "<div class='fontcir' style='font-size:160%;color:green;margin-left:20px;' title='话单接收成功'><b>✔</b></div>";
                          else if (data == "0" || data == "０")
//                          return "处理失败";
                            return "<div class='fontcir' style='font-size:160%;color:red;margin-left:20px;' title='话单接收失败'><b>×</b></div>";
                          else
                            return "<div class='fontcir' style='font-size:160%;color:#ffa500;margin-left:20px;' title='未知状态'><b>?</b></div>";
                        }
                      }, {
                        "sTitle" : "费用",
                        "bSortable" : false,
                        "mData" : "callingcost"
                      } ],
                  "fnDrawCallback" : function(oSettings) {
                    // 表格绘制完成后，去除width属性，使表格可缩放
                    $('#' + oSettings.sTableId).css("width", "");
                  }
                });
  
        // 明细操作事件
        $("#datatableid tbody").on("click", "tr>td>div>a.btn-link", function() {
          var rowNode = this.parentNode.parentNode.parentNode;
          var rowData = datatable.fnGetData(rowNode);
  
          $("#queryAreaId").hide();
          $("#data_table").hide();
          $("#data_table_detail").show();
  
          $("#back_btn").show();
          $("#show").text("被叫号码详细信息");
          var applymodify = require("js/common/pub/src/js/phonebilldetail.js");
          applymodify.init("pub/phonebill.html", "data_table_detail", rowData, param.flagIsv, startIndex);
  
        });
  
        $('#btnquery').click(function() {
          // 蒙版
          loader.loading("数据加载中，请稍后……");
          var startyear = $("#startyearid").val();
          var startmonth = $("#startmonthid").val();
          var endyear = $("#endyearid").val();
          var endmonth = $("#endmonthid").val();
          if (startyear > endyear) {
            bootbox.alert("所选起始年份大于终止年份，请重新选择！");
            return false;
          } else if (startyear == endyear) {
            if (startmonth > endmonth) {
              bootbox.alert("所选起始月份大于终止月份，请重新选择！");
              return false;
            }
          }
          datatable.fnDraw();
          var url = "/pubbase/achievement/export/achievementRecordMonth?queryString=" + getCondition();
//          $('#btn_export').attr("href", url);

          return false;
        });
        
        //重置按钮
        $('#restbtn').click(function() {
          // 蒙版
          loader.loading("数据加载中，请稍后……");
          $('#carrierid').select2("val", "");
          $('#isvid').select2("val", "");
          $('#applicationid').select2("val", "");
          $('#abilityType').select2("val", "");
          $('#sessionid').val("");
          daterangeCom.setRangeToToday();
//          datatable.fnFilter("");
          datatable.fnDraw();
          return false;
        });
  
        //为导出数据按钮绑定url，暂时注释掉了“导出”的按钮
//        var url = "/pubbase/achievement/export/achievementRecordMonth?queryString=" + getCondition();
//        $('#btn_export').attr("href", url);
  
      });
  };
});
